package com.huiyin.ui.moments;

import java.util.ArrayList;

import org.apache.http.Header;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.huiyin.AppContext;
import com.huiyin.R;
import com.huiyin.UIHelper;
import com.huiyin.api.CustomResponseHandler;
import com.huiyin.api.RequstClient;
import com.huiyin.api.URLs;
import com.huiyin.base.BaseActivity;
import com.huiyin.bean.MomentsAppraiseListBean;
import com.huiyin.bean.MomentsAppraiseListBean.AppraiseItem;
import com.huiyin.bean.MomentsShowDetailBean;
import com.huiyin.bean.MomentsShowDetailBean.GoodsMap;
import com.huiyin.ui.classic.ProductsDetailActivity;
import com.huiyin.ui.moments.view.MomentsCommentView;
import com.huiyin.ui.moments.view.MomentsCommentView.CommentItemSelectListener;
import com.huiyin.ui.moments.view.MomentsDetailContentView;
import com.huiyin.ui.user.LoginActivity;
import com.huiyin.utils.AppManager;
import com.huiyin.utils.DialogUtil;
import com.huiyin.utils.DialogUtil.InputDialogListener;
import com.huiyin.utils.ImageManager;
import com.huiyin.utils.JSONParseUtils;
import com.huiyin.utils.ShareUtils;
import com.huiyin.utils.StringUtils;
import com.huiyin.utils.Utils;
import com.huiyin.wight.pulltorefresh.PullToRefreshBase;
import com.huiyin.wight.pulltorefresh.PullToRefreshBase.Mode;
import com.huiyin.wight.pulltorefresh.PullToRefreshBase.OnRefreshListener2;
import com.huiyin.wight.pulltorefresh.PullToRefreshScrollView;

/**
 * 秀场详情
 * 
 * @author zhyao
 * 
 */
public class MomentsDetailActivity extends BaseActivity implements OnClickListener, CommentItemSelectListener,
		OnRefreshListener2<ScrollView> {

	private static final String TAG = "MomentsDetailActivity";

	public static final String INTENT_KEY_SHOW_ID = "spotlight_show_id";

	/** 返回 **/
	private TextView mBackTv;

	/** 分享 **/
	private TextView mShareTv;

	/** scrollview **/
	private PullToRefreshScrollView mScrollView;

	/** 头像 **/
	private ImageView mHeadImg;

	/** 姓名 **/
	private TextView mNameTv;

	/** 时间 **/
	private TextView mTimeTv;

	/** 圈子 **/
	private RelativeLayout mCircleLayout;

	/** 圈子 **/
	private ImageView mCircleImg;

	/** 圈子 **/
	private TextView mCircleTv;

	/** 详情标题 **/
	private TextView mDetailTitleTv;

	/** 详情的图片或者视频view **/
	private MomentsDetailContentView mDetailContentView;

	/** 详情 **/
	private TextView mDetailDescTv;

	/** 打赏布局 **/
	private RelativeLayout mRedpacketLayout;

	/** 打赏 **/
	private ImageView mRedpacketImg;

	/** 打赏 **/
	private TextView mRedpacketTv;

	/** 点赞布局 **/
	private RelativeLayout mLikeLayout;

	/** 点赞 **/
	private ImageView mLikeImg;

	/** 点赞 **/
	private TextView mLikeTv;

	/** 收藏布局 **/
	private RelativeLayout mFavoriteLayout;

	/** 收藏 **/
	private ImageView mFavoriteImg;

	/** 收藏 **/
	private TextView mFavoriteTv;

	/** 关联商品布局 **/
	private RelativeLayout mGoodsLayout;

	/** 关联商品 **/
	private ImageView mGoodsImg;

	/** 关联商品名称 **/
	private TextView mGoodsName;

	/** 关联商品价格 **/
	private TextView mGoodsPrice;

	/** 评论view **/
	private MomentsCommentView mCommentView;

	/** 评论输入框 **/
	private EditText mCommentEdt;

	/** 评论发送按钮 **/
	private ImageView mSendImg;

	/** 秀场id **/
	private String mShowId;

	/** 用户id **/
	private String mUserId;

	/** 回复id **/
	private String mReplyId;

	/** 评论 list **/
	private ArrayList<AppraiseItem> appraiseList;

	/** 是否已打赏过红包 **/
	private boolean hasReward;

	/** 是否点赞 **/
	private boolean isLike;

	/** 点赞数 **/
	private int likeCount;

	/** 是否收藏 **/
	private boolean isFavorite;

	/** 收藏数 **/
	private int favoriteCount;

	/** 当前发布秀场的用户id **/
	private String giveUserId;

	/** 当前发布秀场的用户号码 **/
	private String givePhone;
	
	/** 分享地址 **/
	private String shareUrl;
	
	/** 分享图片 **/
	private String shareImage;
	
	/** 圈子ID **/
	private String circleId;
	
	/** 圈子名 **/
	private String circleName;
	
	/** 分享内容 **/
	private String shareContent;
	
	/** 推荐的商品 **/
	private GoodsMap mRecommendGoods;

	/** 分页： 当前页 **/
	private int pageIndex = 1;

	/** 分页： 每页大小 **/
	private int pageSize = 10;

	/** 分页： 总页数 **/
	private int totalPageNum;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_moments_detail);

		mShowId = getIntent().getStringExtra(INTENT_KEY_SHOW_ID);
		mUserId = AppContext.userId;

		initView();
		initData();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	private void initView() {
		// 导航栏信息
		mBackTv = (TextView) findViewById(R.id.tv_back);
		mShareTv = (TextView) findViewById(R.id.tv_share);
		// 上拉加载下拉刷新
		mScrollView = (PullToRefreshScrollView) findViewById(R.id.scroll_detail);
		mScrollView.setMode(Mode.PULL_FROM_END);
		mScrollView.getLoadingLayoutProxy().setLastUpdatedLabel(Utils.getCurrTiem());
		mScrollView.getLoadingLayoutProxy().setPullLabel("往下拉更新数据...");
		mScrollView.getLoadingLayoutProxy().setRefreshingLabel("正在载入中...");
		mScrollView.getLoadingLayoutProxy().setReleaseLabel("放开更新数据...");
		mScrollView.setOnRefreshListener(this);

		// 头部信息
		mHeadImg = (ImageView) findViewById(R.id.img_head);
		mNameTv = (TextView) findViewById(R.id.tv_name);
		mTimeTv = (TextView) findViewById(R.id.tv_time);
		mCircleLayout = (RelativeLayout) findViewById(R.id.rl_circle);
		mCircleImg = (ImageView) findViewById(R.id.img_circle);
		mCircleTv = (TextView) findViewById(R.id.tv_circle);
		// 详情信息
		mDetailTitleTv = (TextView) findViewById(R.id.tv_detail_title);
		mDetailContentView = (MomentsDetailContentView) findViewById(R.id.view_content);
		mDetailDescTv = (TextView) findViewById(R.id.tv_detail_desc);
		// 打赏
		mRedpacketLayout = (RelativeLayout) findViewById(R.id.rl_redpacket);
		mRedpacketImg = (ImageView) findViewById(R.id.img_redpacket);
		mRedpacketTv = (TextView) findViewById(R.id.tv_redpacket);
		// 点赞
		mLikeLayout = (RelativeLayout) findViewById(R.id.rl_like);
		mLikeImg = (ImageView) findViewById(R.id.img_like);
		mLikeTv = (TextView) findViewById(R.id.tv_like);
		// 收藏
		mFavoriteLayout = (RelativeLayout) findViewById(R.id.rl_favorite);
		mFavoriteImg = (ImageView) findViewById(R.id.img_favorite);
		mFavoriteTv = (TextView) findViewById(R.id.tv_favorite);
		// 关联商品信息
		mGoodsLayout = (RelativeLayout) findViewById(R.id.rl_goods);
		mGoodsImg = (ImageView) findViewById(R.id.img_goods);
		mGoodsName = (TextView) findViewById(R.id.tv_goods_name);
		mGoodsPrice = (TextView) findViewById(R.id.tv_goods_price);
		// 评论
		mCommentView = (MomentsCommentView) findViewById(R.id.view_comment);
		mCommentEdt = (EditText) findViewById(R.id.edt_comment);
		mSendImg = (ImageView) findViewById(R.id.img_send);

		mBackTv.setOnClickListener(this);
		mShareTv.setOnClickListener(this);
		mCircleLayout.setOnClickListener(this);
		mRedpacketLayout.setOnClickListener(this);
		mLikeLayout.setOnClickListener(this);
		mFavoriteLayout.setOnClickListener(this);
		mGoodsLayout.setOnClickListener(this);
		mSendImg.setOnClickListener(this);
		mCommentView.setCommentItemSelectListener(this);
	}

	private void initData() {

		appraiseList = new ArrayList<AppraiseItem>();

		pageIndex = 1;
		
		requestDetail(mShowId, mUserId);
		requestComments(mShowId, pageIndex, pageSize);
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		// 返回
		case R.id.tv_back:
			AppManager.getAppManager().finishActivity();
			finish();
			break;
		// 分享
		case R.id.tv_share:
			sendShare();
			break;
		// 跳转圈子
		case R.id.rl_circle:
			Intent intent1 = new Intent(mContext, MomentsCircleActivity.class);
			intent1.putExtra(MomentsCircleActivity.INTENT_KEY_CIRCLE_ID, circleId);
			intent1.putExtra(MomentsCircleActivity.INTENT_KEY_CIRCLE_NAME, circleName);
			startActivity(intent1);
			break;
		// 打赏
		case R.id.rl_redpacket:
			if (isLogin()) {
				sendBonus();
			}
			break;
		// 点赞
		case R.id.rl_like:
			if (isLogin()) {
				if (!isLike) {
					sendLike();
				}
			}

			break;
		// 收藏
		case R.id.rl_favorite:
			if (isLogin()) {
				if (isFavorite) {
					sendCancleFavorite();
				} else {
					sendFavorite();
				}
			}

			break;
		// 关联商品
		case R.id.rl_goods:
			if (mRecommendGoods != null) {
				Intent intent2 = new Intent(mContext, ProductsDetailActivity.class);
				intent2.putExtra(ProductsDetailActivity.BUNDLE_KEY_GOODS_ID, mRecommendGoods.getID());
				mContext.startActivity(intent2);
			}
			break;
			// 发送评论
		case R.id.img_send:
			if (isLogin()) {
				sendComment();
			}
			break;

		default:
			break;
		}

	}

	/**
	 * 判断是否登录
	 * 
	 * @return
	 */
	private boolean isLogin() {
		if (StringUtils.isBlank(mUserId)) {
			UIHelper.showToast("请先登录");
			Intent intent = new Intent(this, LoginActivity.class);
			startActivity(intent);
			return false;
		}
		return true;
	}
	
	/**
	 * 分享
	 */
	private void sendShare() {
		ShareUtils.showShare(mContext, "汇银商城", shareUrl, shareImage, shareContent);
	}

	/**
	 * 打赏
	 */
	private void sendBonus() {
		
		if(mUserId.equals(giveUserId)) {
			UIHelper.showToast("不能打赏自己");
			return;
		}
		
		DialogUtil.showInputDialog(this, "赠送红包", "请输入红包金额", new InputDialogListener() {

			@Override
			public void onClick(Dialog dialog, String input) {
				
				if(StringUtils.isEmpty(input)) {
					UIHelper.showToast("请输入打赏金额");
					return;
				}
				if(Integer.parseInt(input) > 0) {
					dialog.dismiss();
					requestBouns(mShowId, mUserId, AppContext.mUserInfo.phone, giveUserId, givePhone, input);
				}
				else {
					UIHelper.showToast("不能打赏0元");
				}
			}
		});
	}

	/**
	 * 点赞
	 */
	private void sendLike() {
		requestLike(mShowId, mUserId, "3");
	}

	/**
	 * 收藏
	 */
	private void sendFavorite() {
		requestFavorite(mShowId, mUserId, "3");
	}

	/**
	 * 取消收藏
	 */
	private void sendCancleFavorite() {
		requestCancelFavorite(mShowId, mUserId);
	}

	/**
	 * 发送评论
	 */
	private void sendComment() {
		String commentStr = mCommentEdt.getText().toString();
		if (StringUtils.isEmpty(commentStr)) {
			UIHelper.showToast("请输入评论内容");
			return;
		}

		requestSendComment(mShowId, mUserId, mReplyId, commentStr, "3");

	}

	/**
	 * 请求详情
	 * 
	 * @param showId
	 * @param userId
	 */
	private void requestDetail(String showId, String userId) {
		RequstClient.showDetail(showId, userId, new CustomResponseHandler(this) {
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);

				MomentsShowDetailBean bean = MomentsShowDetailBean.explainJson(content, MomentsDetailActivity.this);
				// 成功
				if (bean.type == 1) {
					try {
						giveUserId = bean.getMap().getShowMap().getUSER_ID();
						givePhone = bean.getMap().getShowMap().getPHONE();
						shareUrl =  bean.getMap().getShareUrl();
						shareContent = bean.getMap().getShowMap().getTITLE();
						refreshDetailUI(bean);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				// 失败
				else {
					UIHelper.showToast(bean.msg);
				}
			}
		});
	}

	/**
	 * 获取评论列表
	 * 
	 * @param showId
	 * @param pageIndex
	 * @param pageSize
	 */
	private void requestComments(String showId, int pageIndex, int pageSize) {
		RequstClient.appraiseList(showId, pageIndex, pageSize, new CustomResponseHandler(this, false) {
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);

				MomentsAppraiseListBean bean = MomentsAppraiseListBean.explainJson(content, MomentsDetailActivity.this);
				// 成功
				if (bean.type == 1) {
					totalPageNum = bean.getTotalPageNum();
					try {
						refreshCommentsUI(bean);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				// 失败
				else {
					UIHelper.showToast(bean.msg);
				}
			}
		});
	}

	/**
	 * 发送评论
	 * 
	 * @param showId
	 * @param userId
	 * @param replyId
	 * @param content
	 * @param origin
	 */
	private void requestSendComment(String showId, String userId, String replyId, String content, String origin) {
		RequstClient.sendAppraise(showId, userId, replyId, content, origin, new CustomResponseHandler(this) {
			@Override
			public void onSuccess(int statusCode, Header[] headers, String content) {
				super.onSuccess(statusCode, headers, content);

				int type = JSONParseUtils.getInt(content, "type");
				String msg = JSONParseUtils.getString(content, "msg");
				UIHelper.showToast(msg);
				// 成功
				if (type == 1) {
					// 清空输入框
					mCommentEdt.setText("");
					mCommentEdt.setHint("");
					// 清空评论列表
					appraiseList.clear();
					// 第一页
					pageIndex = 1;
					// 刷新评论列表
					requestComments(mShowId, pageIndex, pageSize);
				}

			}
		});
	}

	/**
	 * 打赏 赠送红包
	 * 
	 * @param showId
	 * @param userId
	 * @param phone
	 * @param giveUserId
	 * @param giveUserPhone
	 * @param bonus
	 */
	private void requestBouns(String showId, String userId, String phone, String giveUserId, String giveUserPhone,
			String bonus) {
		RequstClient.rewardBonus(showId, userId, phone, giveUserId, giveUserPhone, bonus, new CustomResponseHandler(
				this) {
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);

				int type = JSONParseUtils.getInt(content, "type");
				String msg = JSONParseUtils.getString(content, "msg");
				UIHelper.showToast(msg);
				if (type == 1) {
					hasReward = true;
					String bonus = JSONParseUtils.getString(content, "bonus");
					refreshRedPacketUI(bonus);
				}

			}
		});

	}

	/**
	 * 点赞
	 * 
	 * @param showId
	 * @param userId
	 * @param origin
	 */
	private void requestLike(String showId, String userId, String origin) {
		RequstClient.showLike(showId, userId, origin, new CustomResponseHandler(this) {
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);

				int type = JSONParseUtils.getInt(content, "type");
				if (type == 1) {
					isLike = true;
					likeCount++;
					refreshLikeUI();
				}
			}
		});
	}

	/**
	 * 取消收藏
	 * 
	 * @param showId
	 * @param userId
	 * @param origin
	 */
	private void requestCancelFavorite(String showId, String userId) {
		RequstClient.showCancelCollect(showId, userId, new CustomResponseHandler(this) {
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				int type = JSONParseUtils.getInt(content, "type");
				if (type == 1) {
					isFavorite = false;
					if (favoriteCount > 0) {
						favoriteCount--;
					}
					refreshFavoriteUI();
				}

			}
		});
	}

	/**
	 * 收藏
	 * 
	 * @param showId
	 * @param userId
	 * @param origin
	 */
	private void requestFavorite(String showId, String userId, String origin) {
		RequstClient.showCollect(showId, userId, origin, new CustomResponseHandler(this) {
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				int type = JSONParseUtils.getInt(content, "type");
				if (type == 1) {
					isFavorite = true;
					favoriteCount++;
					refreshFavoriteUI();
				}
			}
		});
	}

	/**
	 * 刷新详情信息
	 * 
	 * @param bean
	 */
	private void refreshDetailUI(MomentsShowDetailBean bean) {
		//圈子信息
		circleName = bean.getMap().getShowMap().getCIRCLE_NAME();
		circleId = bean.getMap().getShowMap().getSPOTLIGHT_CIRCLE_ID();
		
		ImageManager.Load(bean.getMap().getShowMap().getFACE_IMAGE_PATH(), mHeadImg, ImageManager.headOptions);
		mNameTv.setText(bean.getMap().getShowMap().getUSER_NAME());
		mTimeTv.setText(bean.getMap().getShowMap().getCREATE_TIME());
		ImageManager.Load(bean.getMap().getShowMap().getCIRCLE_IMG(), mCircleImg, ImageManager.squareOptions);
		mCircleTv.setText(bean.getMap().getShowMap().getCIRCLE_NAME());
		mDetailTitleTv.setText(bean.getMap().getShowMap().getTITLE());
		mDetailDescTv.setText(bean.getMap().getShowMap().getCONTENT());
		
		// 视频
		if (bean.getMap().getShowMap().getTYPE() == 3) {
			mDetailContentView.setViewData(URLs.IMAGE_URL + bean.getMap().getShowMap().getSHOW_FILE(), URLs.IMAGE_URL
					+ bean.getMap().getShowMap().getVIDEO_IMG(), "");
			shareImage = bean.getMap().getShowMap().getVIDEO_IMG();
		}
		// 图片
		else {
			mDetailContentView.setViewData(bean.getMap().getShowMap().getSHOW_IMG());
			String imgUrls = bean.getMap().getShowMap().getSHOW_IMG();
			if(!StringUtils.isEmpty(imgUrls)) {
				shareImage = imgUrls.split(",")[0];
			} 
			else {
				shareImage = "";
			}
		}

		if (bean.getMap().getIsReward() == 1) {
			hasReward = true;
		}
		else {
			hasReward = false;
		}
		refreshRedPacketUI(bean.getMap().getBonus());

		// 是否点赞 1：是 0：否
		if (bean.getMap().getIsLike() == 1) {
			isLike = true;
		} else {
			isLike = false;
		}
		likeCount = bean.getMap().getLikeCount();
		refreshLikeUI();

		// 是否收藏 1：是 0：否
		if (bean.getMap().getIsCollect() == 1) {
			isFavorite = true;
		} else {
			isFavorite = false;
		}
		favoriteCount = bean.getMap().getCollectCount();
		refreshFavoriteUI();

		refreshRecommendGoodsUI(bean.getMap().getGoodsMap());
	}

	/**
	 * 设置推荐商品信息
	 * 
	 * @param goodsMap
	 */
	private void refreshRecommendGoodsUI(GoodsMap goodsMap) {
		mRecommendGoods = goodsMap;
		if (goodsMap != null) {
			mGoodsLayout.setVisibility(View.VISIBLE);
			ImageManager.Load(goodsMap.getIMG(), mGoodsImg, ImageManager.squareOptions);
			mGoodsName.setText(goodsMap.getGOODS_NAME());
			mGoodsPrice.setText(String.format(getString(R.string.goods_price), goodsMap.getPRICE()));
		} else {
			mGoodsLayout.setVisibility(View.GONE);
		}

	}

	/**
	 * 设置评论列表数据
	 * 
	 * @param bean
	 */
	private void refreshCommentsUI(MomentsAppraiseListBean bean) {
		if(bean.getAppraiseList() != null) {
			appraiseList.addAll(bean.getAppraiseList());
		}
		mCommentView.setData(appraiseList);
		mScrollView.onRefreshComplete();
	}

	/**
	 * 设置打赏
	 */
	private void refreshRedPacketUI(String bonus) {
		if (hasReward) {
			mRedpacketImg.setBackgroundResource(R.drawable.shape_circle_red);
		}
		mRedpacketTv.setText(String.format(getString(R.string.bonus_count), bonus));
	}

	/**
	 * 设置点赞信息
	 */
	private void refreshLikeUI() {
		if (isLike) {
			mLikeImg.setBackgroundResource(R.drawable.shape_circle_red);
		} else {
			mLikeImg.setBackgroundResource(R.drawable.shape_circle_gray);
		}
		mLikeTv.setText(String.format(getString(R.string.like_count), likeCount));

	}

	/**
	 * 设置收藏信息
	 */
	private void refreshFavoriteUI() {
		if (isFavorite) {
			mFavoriteImg.setBackgroundResource(R.drawable.shape_circle_red);
		} else {
			mFavoriteImg.setBackgroundResource(R.drawable.shape_circle_gray);
		}
		mFavoriteTv.setText(String.format(getString(R.string.favorite_count), favoriteCount));

	}

	/**
	 * 选中需要回复的评论
	 */
	@Override
	public void onCommentSelect(AppraiseItem appraiseItem) {
		mReplyId = appraiseItem.getUSER_ID();
		mCommentEdt.setHint(String.format(getString(R.string.reply_hint), appraiseItem.getUSER_NAME()));
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {

	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
		Log.d(TAG, "onLodeMore");
		pageIndex++;
		if(pageIndex <= totalPageNum) {
			requestComments(mShowId, pageIndex, pageSize);
		}
		else {
			new Handler().postDelayed(new Runnable() {
				
				@Override
				public void run() {
					mScrollView.onRefreshComplete();
				}
			}, 100);
		}
	}

}
